<?php
/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided data can identity the user.
 * 
 * Yawii 版权所有 @ 2012
 */
class UserIdentity extends CUserIdentity
{
	const ERROR_LOCKED = 4;	// account is locked
	const ERROR_EXPIRED = 5;// account is expired
	
	// Need to store the user's ID:
	private $_id;
	public function getId() {
		return $this->_id;
	}
	public function setId($id) {
		$this->_id = $id;
	}

	/**
	 * Authenticates a user with database.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$sql = 'SELECT password, id, category_key, name, address, biz_area, city, postcode, url_logo, status 
			FROM tbl_merchant_account WHERE email=:email';
		// fetch password and username
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql);
		$row = $command->queryRow(true, array('email' => $this->username));
		$connection->active = false;
		
		// check the password with md5
		if (empty($row)) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		} else {
			//DB password with hash32(md5(string))
			$pasword_in_db = BUtils::Hash32(md5($this->password));
			if ($row['password'] === $pasword_in_db) {
				switch($row['status']) {
					case self::ERROR_LOCKED:
						$this->errorCode = $row['status'];
						break;
					case self::ERROR_EXPIRED:
						$this->errorCode = $row['status'];
						break;
					default:
						$this->errorCode = self::ERROR_NONE;
						$this->_id = $row['id'];
						$this->setState('category_key', $row['category_key']);
						$this->setState('name', $row['name']);
						$this->setState('address', $row['address']);
						$this->setState('biz_area', $row['biz_area']);
						$this->setState('postcode', $row['postcode']);
						$this->setState('city', $row['city']);
						$this->setState('logo', $row['url_logo']);
						$this->setState('status', $row['status']);
						$this->setState('loginTime', time());
						break;
				}
			} else {
				$this->errorCode = self::ERROR_PASSWORD_INVALID;
			}
		}
		
		return (self::ERROR_NONE == $this->errorCode);
	}
	
	/**
	 * Reset a account for current merchant.
	 * @return boolean 
	 */
	public function resetAccount($password, $email) {
		$sql_update = 'UPDATE tbl_merchant_account SET update_timestamp=NOW()';
		$params = array(':id' => Yii::app()->user->id); // Here must use login user ID.
		if (!empty($password)) {
			$pasword_in_db = BUtils::Hash32(md5($password));
			$params[':password'] = $pasword_in_db;
			$sql_update .= ', password=:password ';
		}
		
		if (!empty($email)) {
			$params[':email'] = $email;
			$sql_update .= ', email=:email ';
		}
		$sql_update .= ' WHERE id=:id ';
		
		try {
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_update);
			$command->execute($params);
			$connection->active = false;
			$this->errorCode = self::ERROR_NONE;
		} catch (Exception $ex) {
			BUtils::Logging('ERROR', $ex->getMessage() . ' | ' . $ex->getTraceAsString());
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		
		return (!$this->errorCode);
	}
	
	public function resetPassword() {
		$sql_update = 'UPDATE tbl_merchant_account SET update_timestamp=NOW(), password=:password WHERE email=:email ';
		$pasword_in_db = BUtils::Hash32(md5($this->password));
		$params = array(
			':email' => $this->username,
			':password' => $pasword_in_db,
		);
		try {
			$connection = Yii::app()->db;
			$command = $connection->createCommand($sql_update);
			$command->execute($params);
			$connection->active = false;
			$this->errorCode = self::ERROR_NONE;
		} catch (Exception $ex) {
			BUtils::Logging('ERROR', $ex->getMessage() . ' | ' . $ex->getTraceAsString());
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		
		return (!$this->errorCode);
	}
	
	/**
	 * Create an account for sign up page.
	 * @return boolean 
	 */
	public function createAccount() {
		//save password with hash32(md5(string))
		$pasword_in_db = BUtils::Hash32(md5($this->password));
		
		// save md5(password) and username
		try {
			$connection = Yii::app()->db;
			$command = $connection->createCommand('INSERT INTO tbl_merchant_account (email, password, status) VALUES (:email, :password, 1)');
			$command->execute(array('email' => $this->username, 'password' => $pasword_in_db));
			$this->errorCode = self::ERROR_NONE;
			$connection->active = false;
		} catch (Exception $ex) {
			BUtils::Logging('ERROR', $ex->getMessage() . ' | ' . $ex->getTraceAsString());
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}

		return (!$this->errorCode);
	}
}